﻿using FadeJSON;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Work.Weixin
{
    public partial class wxCorporation
    {
        private string corpid;
        private static readonly HttpClient httpClient = new HttpClient();

        public wxCorporation(string corpid)
        {
            this.corpid = corpid;
        }

        public string GetAccessToken(
            IAccessTokenCache tokenCache, string appSecret, int expired_time = 100)
        {
            string access_token = string.Empty;

            if (!tokenCache.TryGetAccessToken(expired_time, out access_token))
            {
                string gettoken = string.Format(
@"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}",
                    this.corpid, appSecret);
                var responseString = httpClient.GetStringAsync(gettoken).Result;
                JsonBaseType jsonObj = Json.FromString(responseString);
                access_token = jsonObj.Value["access_token"].Value;
                tokenCache.UpdateCache(responseString, DateTime.Now);
            }

            return access_token;
        }

        public void GetMedia(string access_token, string media_id)
        {
            string get = string.Format(
@"https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}",
                   access_token, media_id);
            var response = httpClient.GetAsync(get).Result;
            using (var s = response.Content.ReadAsStreamAsync().Result)
            {
                using (var fs = new FileStream(string.Format(@"Media\{0}",
                    response.Content.Headers.ContentDisposition.FileNameStar), FileMode.Create))
                {
                    const int bufferSize = 1024;
                    var buffer = new byte[bufferSize];
                    int totalLength = 0;
                    int length = 0;
                    length = s.Read(buffer, 0, bufferSize);
                    while (length != 0)
                    {
                        totalLength += length;
                        fs.Write(buffer, 0, length);
                        length = s.Read(buffer, 0, bufferSize);
                    }
                }
            }
            //JsonObject jsonObj = Json.FromString(responseString);
            //access_token = jsonObj["access_token"].String;
        }
    }

}

